package com.changcheng.aspect;
import com.changcheng.pojo.User;
import com.changcheng.service.RecordService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Component
public class ServiceAspect {
    @Autowired
    private RecordService recordService;
    @Pointcut("@annotation(com.changcheng.aspect.ServiceOperation)")
    public void log() {
    }
    /*登录成功后，对数据库填写登录日志信息*/
    @AfterReturning(value = "log()",returning = "returnValue")
    public void ServiceOperation(JoinPoint joinPoint,Object returnValue) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        String username=user.getName();
        int userId=user.getId();
        String operation_result="";
        MethodSignature signature=(MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        ServiceOperation annotation = method.getAnnotation(ServiceOperation.class);
        if(returnValue instanceof Boolean){
            boolean result=(Boolean)returnValue;
            operation_result=result?"成功":"失败";
        }
        recordService.addRecord(userId,username,annotation.value(),operation_result);
    }
}
